<?php

namespace App\Model\PssModel;

use App\Model\BaseModel\BasePssModel;
use App\Service\Code\Normal;
use Hyperf\DbConnection\Db;

class FreightTemplateArea extends BasePssModel
{
    public $table = 'freight_template_area';

    //用户下单地址高德解析缓存地址
    const USER_ADDRESS_CACHE_KEY = 'user_address_cache_key';

    /**
     * 获取运费模板区域分组
     * @param array $tpl_ids
     */
    public function getGoodsTemplateByIds( array $tpl_ids = [] )
    {
        $tpl_ids = array_unique($tpl_ids);
        $tpl_ids = array_filter($tpl_ids);
        if( empty($tpl_ids) ) {
            return [];
        }

        $list = $this
            ->select([
                'freight_template_area.id as tda_id',
                'freight_template_area.template_id',
                'freight_template_area.init_weight',
                'freight_template_area.init_money',
                'freight_template_area.increase_weight',
                'freight_template_area.increase_money',
                'freight_template_area.type',
                Db::raw("IFNULL(tdal.area_id,0) as tda_area_id")
            ])
            ->leftJoin('freight_template_area_list as tdal', 'tdal.tda_id', '=', 'freight_template_area.id')
            ->whereIn('freight_template_area.template_id',$tpl_ids)
            ->whereIn('freight_template_area.type',[1,2])
            ->get()
            ->toArray();


        if( empty($list) ) {
            return [];
        }
        $list_map = $noSaleArea = [];
        foreach ($list as & $item )
        {
            //禁售区域
            if ($item['type'] == 2){
                $noSaleArea[] = $item['tda_area_id'];
            }else{
                //运费最高单价  = 首重价格 + 续重价格单价/KG
                $item['freight_all'] = bcadd((string)$item['init_money'], (string)$item['increase_money'],2) * 100;
                $list_map[$item['template_id']][$item['tda_area_id']] = $item;
                unset($item);
            }

        }

        return ['templateList' => $list_map,'noSaleArea' => $noSaleArea];
    }


    /**
     * 获取价格最高的运费模板（最高规则：首重价格 + 续重价格/kg）
     * @param array $template
     * @param array $needTemplateIds
     * @param $weight
     */
    public function getMostHighFreightMoney( array $templateList = [] , array $needTemplateIds = [] )
    {

        $freight_template_ids = array_unique($needTemplateIds);
        //获取当前商品分组的运费模板情况
        $current_template_list = [];
        foreach ($freight_template_ids as $key => $template_id )
        {
            if ( isset($templateList[$template_id]) ) {
                $current_template_list[$template_id] = $templateList[$template_id];
            }
            unset($freight_template_ids[$key]);
        }

        //获取运费综合值最大的一个模板
        $price_template=[];
        if ($current_template_list){
            $price_arr      = array_column($current_template_list,null,'freight_all');
            $max_price      = max(array_keys($price_arr));
            $price_template = $price_arr[$max_price];
        }

        return Normal::returnCode(Normal::SUC,"运费模板获取成功",$price_template);
    }


    /**
     * 更具模板和重量计算金额
     * @param array $template
     * @param $weight
     */
    public function getFreightMoneyByTemplateAndWeight( array $template = [] , $weight = 0 )
    {
        if (empty($template)){
            return 0;
        }
        $init_weight        = $template['init_weight'];
        $init_money         = $template['init_money'];
        $increase_weight    = $template['increase_weight'];
        $increase_money     = $template['increase_money'];
        //首重
        $money              = $init_money;
        if( $weight > $init_weight ) {
            //续重
            if( $increase_weight > 0 )  {
                $less_weight    = ceil($weight - $init_weight);
                $less_n         = bcdiv((string)$less_weight, (string)$increase_weight,1);
                $less_n         = ceil($less_n);
                $less_money     = bcmul((string)$less_n, (string)$increase_money,2);
                $money          = bcadd((string)$money, (string)$less_money,2);
            }
        }
        return $money;
    }

}